package it.vgnf.ejb3.ejb;

import com.sun.istack.logging.Logger;
import it.vgnf.ejb3.beans.MovimentoMonetario;
import it.vgnf.ejb3.utils.MovimentoMonetarioException;

import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

@MessageDriven(mappedName = "jms/MovimentiMonetariQueue", activationConfig = {
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue")
})
public class CardListaMovimentiMessageBean implements MessageListener {

    private LMManagementRemote lm;
    private final static String ORB_PORT = "3700";

    public CardListaMovimentiMessageBean() {
        try {
            Properties properties = new Properties();
            properties.setProperty("org.omg.CORBA.ORBInitialPort", ORB_PORT);

            Context ctx = new InitialContext(properties);
            lm = (LMManagementRemote) ctx.lookup("java:global/CardListaMovimentiDBProject/LMManagement");
        } catch (NamingException ne) {
            Logger.getLogger(CardListaMovimentiMessageBean.class.getName(), getClass()).log(Level.SEVERE, ne.getMessage());
        }
    }

    @Override
    public void onMessage(Message message) {
        try {
            /*
             * recuperare i dati del messaggio che ci verrà inviato dall'esterno
             */
            String property = message.getStringProperty("Task");
            Logger.getLogger(CardListaMovimentiMessageBean.class.getName(), getClass()).log(Level.INFO, property);

            if (message instanceof ObjectMessage) {
                ObjectMessage objMessage = (ObjectMessage) message;
                Object obj = objMessage.getObject();
                ArrayList<MovimentoMonetario> movimenti = (ArrayList<MovimentoMonetario>) obj;

                if (property.equalsIgnoreCase("insert")) {

                    lm.insertMovimenti(movimenti);

                }
            }
        } catch (MovimentoMonetarioException ex) {
            java.util.logging.Logger.getLogger(CardListaMovimentiMessageBean.class.getName()).log(Level.SEVERE, null, ex);

        } catch (JMSException ex) {
            java.util.logging.Logger.getLogger(CardListaMovimentiMessageBean.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
